package com.hanhai.material.scheduling.controller;

import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.SysProductRecordInto;
import com.hanhai.material.device.service.AsyncService;
import com.hanhai.material.scheduling.entity.SysProductPeople;
import com.hanhai.material.scheduling.service.SysProductPeopleService;
import com.hanhai.material.utils.redis.RedisUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;


import static com.hanhai.material.scheduling.entity.table.SysProductPeopleTableDef.SYS_PRODUCT_PEOPLE;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.mybatisflex.core.query.QueryMethods.distinct;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2024/04/19 16:20:27
 */
@RestController
@RequestMapping("/product_people")
@Log4j2
public class SysProductPeopleController {

    @Autowired
    private SysProductPeopleService sysProductPeopleService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 添加。
     *
     * @param sysProductPeople
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    public Result<?> save(@RequestBody SysProductPeople sysProductPeople) {

//        sysProductPeople.setId(UUID.randomUUID().toString());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String workDate = simpleDateFormat.format(sysProductPeople.getWorkDate());
        boolean result=false;
        String id = workDate + sysProductPeople.getUserId() + sysProductPeople.getWorkTimeIndex().replace("点", "") + sysProductPeople.getMachineName() + sysProductPeople.getWorkPlanId();
        if(redisUtil.hget("scheduling",id)!=null){
            result=this.sysProductPeopleService.updateById(sysProductPeople);
            return result ? ResultTool.success() : ResultTool.fail();
        }
        redisUtil.hset("scheduling",id,id,24*60*60*2);
        sysProductPeople.setId(id);
        log.error("SysProductPeople:" + sysProductPeople);

        try {
            result= this.sysProductPeopleService.save(sysProductPeople);
            return result ? ResultTool.success(sysProductPeople) : ResultTool.fail();
        }catch (Exception e){
            log.error("Excep:",e);
            result=this.sysProductPeopleService.updateById(sysProductPeople);
            return result ? ResultTool.success() : ResultTool.fail();
        }

    }

    @Autowired
    AsyncService asyncService;

    @PostMapping("saveBatch")
    public Result<?> saveBatch(@RequestBody List<SysProductPeople> sysProductPeopleList) {
//        List<SysProductPeople> add=new ArrayList<>();
//        List<SysProductPeople> update=new ArrayList<>();
//        for (SysProductPeople productPeople : sysProductPeopleList) {
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
//            String workDate = simpleDateFormat.format(productPeople.getWorkDate());
//            log.error("SysProductPeople:" + productPeople);
//            String id = workDate + productPeople.getUserId() + productPeople.getWorkTimeIndex().replace("点", "") + productPeople.getMachineName() + productPeople.getWorkPlanId();
//            if(redisUtil.hget("scheduling",id)!=null){
//                productPeople.setId(id);
//                update.add(productPeople);
//            }else{
//                productPeople.setId(id);
//                add.add(productPeople);
//            }
//        }
//        try {
//            this.sysProductPeopleService.updateBatch(update);
//            this.sysProductPeopleService.saveBatch(add);
//        }catch (Exception e){
//
//        }
        CountDownLatch countDownLatch=new CountDownLatch(1);
        this.asyncService.saveProductPeopleBatch(sysProductPeopleList,countDownLatch);
        return  ResultTool.success(sysProductPeopleList);
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public Result<?> remove(@PathVariable String id) {
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_PEOPLE.ID.eq(id));
        boolean result = this.sysProductPeopleService.remove(queryWrapper);
        log.error(queryWrapper.toSQL());
        return result ? ResultTool.success() : ResultTool.fail();
    }

    @PostMapping("/removeBatch")
    public Result<?> removeBatch(@RequestBody List<SysProductPeople> sysProductPeopleList) {
        boolean result = false;

        for(SysProductPeople productPeople:sysProductPeopleList){
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_PRODUCT_PEOPLE.USER_ID.eq(productPeople.getUserId()));
            queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_DATE.eq(fromDateToString("yyyy-MM-dd", productPeople.getWorkDate())));
            queryWrapper.where(SYS_PRODUCT_PEOPLE.SHIFT.eq(productPeople.getShift()));
            queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_PLAN_ID.eq(productPeople.getWorkPlanId()));
            log.error("SysQL：{}",queryWrapper.toSQL());
            result=this.sysProductPeopleService.remove(queryWrapper);
        }
        return result ? ResultTool.success() : ResultTool.fail();
    }
    @PostMapping("/history")
    public Result<?> removeBatch(@RequestBody SysProductPeople productPeople) {
        LocalDate localDate=productPeople.getWorkDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate yesterday=localDate.minusDays(1);
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_DATE.eq(yesterday));
        queryWrapper.where(SYS_PRODUCT_PEOPLE.SHIFT.eq(productPeople.getShift()));
        queryWrapper.where(SYS_PRODUCT_PEOPLE.MACHINE_AREA.eq("成型间接"));
        List<SysProductPeople> sysProductPeopleList=this.sysProductPeopleService.list(queryWrapper);
        int listSize=sysProductPeopleList.size();
        if(listSize>0){
            int count=(listSize/20)+1;
            CountDownLatch countDownLatch=new CountDownLatch(count);
            int startIndex=0;
            int endIndex=0;
            for(int i=1;i<=count;i++){
                startIndex=endIndex;
                endIndex=startIndex*i;
                if(endIndex>listSize||i==count){
                    endIndex=listSize;
                }
                List<SysProductPeople> productPeopleList=sysProductPeopleList.subList(startIndex,endIndex);
                this.asyncService.getHistoryPeople(productPeopleList,countDownLatch);
            }
        }
        return ResultTool.success();
    }

    /**
     * 根据主键更新。
     *
     * @param sysProductPeople
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody SysProductPeople sysProductPeople) {
        return sysProductPeopleService.updateById(sysProductPeople);
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @PostMapping("list")
    public Result<?> list(@RequestBody SysProductPeople productPeople) {
        QueryWrapper queryWrapper = QueryWrapper.create();

        queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_DATE.eq(fromDateToString("yyyy-MM-dd", productPeople.getWorkDate())));
        queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_TIME_INDEX.eq(productPeople.getWorkTimeIndex()));
        queryWrapper.where(SYS_PRODUCT_PEOPLE.MACHINE_NAME.eq(productPeople.getMachineName()));
        queryWrapper.where(SYS_PRODUCT_PEOPLE.SHIFT.eq(productPeople.getShift()));
        queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_PLAN_ID.eq(productPeople.getWorkPlanId()));
        if (productPeople.getWorkShopName().startsWith("成型")) {
            queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_SHOP_NAME.eq("成型中心").or(SYS_PRODUCT_PEOPLE.WORK_SHOP_NAME.eq("成型车间")));
        } else {
            queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_SHOP_NAME.eq(productPeople.getWorkShopName()));
        }

        List<SysProductPeople> productPeopleList = this.sysProductPeopleService.list(queryWrapper);
        log.error("SQL:{}", queryWrapper.toSQL());
        return productPeopleList.isEmpty() ? ResultTool.fail() : ResultTool.success(productPeopleList);
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public SysProductPeople getInfo(@PathVariable Serializable id) {
        return sysProductPeopleService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<SysProductPeople> page(Page<SysProductPeople> page) {
        return sysProductPeopleService.page(page);
    }


    @PostMapping("/listByCondition")
    public Result<?> listByCondition(@RequestBody SysProductPeople sysProductPeople){
        log.error("Start:{}",System.currentTimeMillis());
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_DATE.eq(fromDateToString("yyyy-MM-dd",sysProductPeople.getWorkDate())));
        queryWrapper.where(SYS_PRODUCT_PEOPLE.SHIFT.eq(sysProductPeople.getShift()));
        queryWrapper.select(distinct(SYS_PRODUCT_PEOPLE.MACHINE_NAME),SYS_PRODUCT_PEOPLE.WORK_PLAN_ID,SYS_PRODUCT_PEOPLE.MACHINE_AREA);
        queryWrapper.orderBy(SYS_PRODUCT_PEOPLE.MACHINE_AREA,true);
        queryWrapper.orderBy(SYS_PRODUCT_PEOPLE.MACHINE_NAME,true);
        RelationManager.addIgnoreRelations("bom");
//        RelationManager.addExtraConditionParam("shift",sysProductPeople.getShift());
//        RelationManager.addExtraConditionParam("workDate",fromDateToString("yyyy-MM-dd",sysProductPeople.getWorkDate()));
        List<SysProductPeople> sysProductPeopleList=this.sysProductPeopleService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        log.error("SQL:{}",queryWrapper.toSQL());
        for(SysProductPeople productPeople:sysProductPeopleList){
            queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_PRODUCT_PEOPLE.SHIFT.eq(sysProductPeople.getShift()));
            queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_DATE.eq(fromDateToString("yyyy-MM-dd",sysProductPeople.getWorkDate())));
            queryWrapper.where(SYS_PRODUCT_PEOPLE.WORK_PLAN_ID.eq(productPeople.getWorkPlanId()));
            queryWrapper.where(SYS_PRODUCT_PEOPLE.MACHINE_NAME.eq(productPeople.getMachineName()));
            queryWrapper.where(SYS_PRODUCT_PEOPLE.MACHINE_AREA.eq(productPeople.getMachineArea()));
            List<SysProductPeople> productPeopleList=this.sysProductPeopleService.list(queryWrapper);
            log.error("SQL!:{}",queryWrapper.toSQL());
            List<SysProductPeople> stringList=new ArrayList<>();
            List<SysProductPeople> productPeopleList1=new ArrayList<>();
            for(SysProductPeople productPeople1:productPeopleList){
                SysProductPeople productPeople2=new SysProductPeople();
                productPeople2.setJobNo(productPeople1.getJobNo());
                productPeople2.setUserName(productPeople1.getUserName());
                productPeople2.setMachinePosition(productPeople1.getMachinePosition());
                if(!stringList.contains(productPeople2)){
                    stringList.add(productPeople2);

//                    productPeopleList1.add(productPeople1);
                }
            }
            productPeople.setList(stringList);
//            productPeople.setProductPeopleList(productPeopleList);
        }
        log.error("End:{}",System.currentTimeMillis());

        return ResultTool.fail(sysProductPeopleList);

    }
}
